package com.gxa.community.admin.jms;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxa.community.admin.mapper.MessageIdMapper;
import com.gxa.community.admin.mapper.OperateTicketCodeMapper;
import com.gxa.community.admin.mapper.OperateTicketMapper;
import com.gxa.community.core.pojo.domain.MessageId;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.Serializable;

@Slf4j
@Component
public class CouponStatusListener {

    @Autowired
    private MessageIdMapper messageIdMapper;

    @Autowired
    private OperateTicketMapper operateTicketMapper;

    @Autowired
    private OperateTicketCodeMapper operateTicketCodeMapper;

    @JmsListener(destination = "updateCustomerCoupon",containerFactory = "containerFactory")
    public synchronized void updateCouponStatus(Message message, Session session) throws JMSException {
        //利用messageID防止重复消费
        String jmsMessageID = message.getJMSMessageID();
        //去数据库中查询是否有
        MessageId messageId = messageIdMapper.selectOne(new LambdaQueryWrapper<MessageId>().eq(MessageId::getMsgId, jmsMessageID));
        if (messageId!=null){
            message.acknowledge();
            return;
        }
        ActiveMQObjectMessage activeMQObjectMessage = (ActiveMQObjectMessage) message;
        Serializable couponId = activeMQObjectMessage.getObject();
        String ticketCode = operateTicketMapper.selectCouponNoById((Integer) couponId);
        operateTicketCodeMapper.updateCustomerCouponStatus(ticketCode);
        messageId.setMsgId(jmsMessageID);
        messageId.setStatus(1);
        messageId.setTime(System.currentTimeMillis());
        messageIdMapper.insert(messageId);
    }
}
